package com.zbf.auth.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zbf.auth.service.MenuService;
import com.zbf.auth.user.Menu;
import com.zbf.common.entity.ResponseResult;
import com.zbf.common.entity.ResponseResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 作者: LCG
 * 日期: 2020/6/2 17:21
 * 描述:
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MenuService menuService;

    @RequestMapping("/getAuthMenu")
    public ResponseResult getAuthList(@RequestBody Map<String,Object> map){
        //redis缓存中读取menu列表
        String authMenuId="AUTHMENU" + map.get("userId");
        String menuList = redisTemplate.opsForValue().get(authMenuId);
        //将JSON串转为对象
        JSONArray jsonArray = JSON.parseArray(menuList);

        ResponseResult responseResult = ResponseResult.getResponseResult();
        responseResult.setCode(ResponseResultEnum.SECCESS.getCode());
        responseResult.setSuccess("ok");
        responseResult.setResult(jsonArray);

        return responseResult;
    }


    /**
     * 用来展示权限菜单列表
     * @return
     */
    @RequestMapping("/getAllMenu")
    public String getAllMenu(){
        //先从缓存中获取数据
        String authofallmenus = redisTemplate.opsForValue().get("AUTHOFALLMENUS");
        //如果获取不到则进行数据库查询然后再放入缓存中
        if(authofallmenus==null||authofallmenus.equals("")){
            List<Menu> allMenu = menuService.getAllMenu();

            String toJSONString = JSON.toJSONString(allMenu);

            //加入缓存下次获取直接从缓存获取，提升用户体验
            redisTemplate.opsForValue().set("AUTHOFALLMENUS",toJSONString);
            //设置过期时间
            redisTemplate.expire("AUTHOFALLMENUS",30,TimeUnit.DAYS);
            //返回数据
            return toJSONString;
        }else{
            return authofallmenus;
        }

    }

}
